<template>
  <div class="app-container">
    <div class="filter-container">
      <template>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-input
              v-model="listQuery.code"
              placeholder="请输入激活码查询"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="4">
            <el-input
              v-model="listQuery.phone"
              placeholder="请输入手机号查询"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="10">
            <el-select
              v-model="typeValue"
              placeholder="按类型查询"
              clearable
              @change="onSelectTypeClick"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="expiredTypeValue"
              placeholder="按过期/未过期查询"
              clearable
              @change="onSelectExpiredClick"
            >
              <el-option
                v-for="item in expiredOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-button type="primary" icon="plus" @click="getList"
              >查询
            </el-button>
          </el-col>

          <el-col :span="6">
            <el-button type="primary" icon="plus" @click="showCreate"
              >新增激活码
            </el-button>
          </el-col>

          <el-col :span="6" style="margin-top: 5px">
            <el-button type="danger" icon="delete" @click="removeMulityCode"
              >批量删除
            </el-button>
          </el-col>
        </el-row>
      </template>
    </div>
    <el-table
      style="margin-top: 12px"
      :data="list"
      v-loading="listLoading"
      border
      fit
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      highlight-current-row
    >
      <el-table-column :selectable="checkSelect" type="selection" width="55" />
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"> </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="激活码"
        prop="code"
        style="width: 60px"
      ></el-table-column>
      <el-table-column
        align="center"
        label="生成时间"
        prop="createTime"
        width="170"
      ></el-table-column>
      <el-table-column align="center" label="类型" width="80">
        <template slot-scope="scope">
          <span v-text="getCodeType(scope.$index)"> </span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="已绑定手机号"
        prop="phone"
        width="170"
      ></el-table-column>
      <el-table-column
        align="center"
        label="激活时间"
        prop="activeTime"
        width="170"
      ></el-table-column>
      <el-table-column align="center" label="到期时间" width="170">
        <template slot-scope="scope">
          <div class="vertical">
            <span v-text="getExpirationTime(scope.row)"></span>
            <span class="text-expired" v-if="checkIfExpired(scope.row)"
              >已过期</span
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="管理" width="220">
        <template slot-scope="scope">
          <el-button
            type="danger"
            icon="delete"
            @click="removeCode(scope.$index)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 5px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="listQuery.pageNum"
      :page-size="listQuery.pageRow"
      :total="totalCount"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <el-dialog :title="createCodeTitle" :visible.sync="dialogFormVisible">
      <el-form
        class="small-space"
        label-position="left"
        label-width="100px"
        style="width: 300px; margin-left: 50px"
      >
        <el-form-item label="激活码类型" required>
          <el-select
            v-model="createTypeValue"
            placeholder="请选择激活码类型"
            clearable
          >
            <el-option
              v-for="item in createOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-model="createCountValue" label="数量" required>
          <el-input-number v-model="createCountValue" :min="1" :max="30" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="success" @click="createCode">创 建</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      totalCount: 0, //分页组件--数据总条数
      list: [], //表格的数据
      listLoading: false, //数据加载等待动画
      listQuery: {
        code: "",
        phone: "",
        type: "",
        pageNum: 1, //页码
        pageRow: 10, //每页条数
      },
      roles: [], //角色列表
      dialogStatus: "create",
      dialogFormVisible: false,
      createCodeTitle: "新增激活码",
      options: [
        {
          value: "0",
          label: "全部",
        },
        {
          value: "1",
          label: "1天",
        },
        {
          value: "2",
          label: "1个月",
        },
        {
          value: "3",
          label: "1年",
        },
      ],
      createOptions: [
        {
          value: "1",
          label: "1天",
        },
        {
          value: "2",
          label: "1个月",
        },
        {
          value: "3",
          label: "1年",
        },
      ],
      expiredOptions: [
        {
          value: "0",
          label: "全部",
        },
        {
          value: "1",
          label: "未过期",
        },
        {
          value: "2",
          label: "已过期",
        },
        {
          value: "3",
          label: "未激活",
        },
      ],
      typeValue: "0",
      expiredTypeValue: "0",
      createTypeValue: "",
      createCountValue: 1,
      multipleSelection: [],
    };
  },
  created() {
    this.getList();
    if (this.hasPerm("user:add") || this.hasPerm("user:update")) {
      this.getAllRoles();
    }
  },
  computed: {
    ...mapGetters(["userId"]),
  },
  methods: {
    getAllRoles() {
      this.api({
        url: "/user/getAllRoles",
        method: "get",
      }).then((data) => {
        this.roles = data.list;
      });
    },
    getList() {
      console.log("getList");
      this.listQuery.type = this.typeValue;
      this.listQuery.expiredType = this.expiredTypeValue;
      //查询列表
      this.listLoading = true;
      this.api({
        url: "/wx/code/codes",
        method: "get",
        params: this.listQuery,
      }).then((data) => {
        this.listLoading = false;
        this.list = data.list;
        this.totalCount = data.totalCount;
      });
    },
    handleSizeChange(val) {
      //改变每页数量
      this.listQuery.pageRow = val;
      this.handleFilter();
    },
    handleCurrentChange(val) {
      //改变页码
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleFilter() {
      //查询事件
      this.listQuery.pageNum = 1;
      this.getList();
    },
    getIndex($index) {
      //表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1;
    },
    showCreate() {
      //显示新增对话框
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    createCode() {
      console.log(this.createTypeValue, this.createCountValue);
      if (
        this.createTypeValue == null ||
        this.createTypeValue.length == 0 ||
        this.createTypeValue == "0"
      ) {
        this.$message.error("请选择类型");
        return;
      }
      var data = {
        type: this.createTypeValue,
        count: this.createCountValue,
      };
      //添加新用户
      this.api({
        url: "/wx/code",
        method: "post",
        data: data,
      }).then(() => {
        this.$message.success("创建成功");
        this.getList();
        this.dialogFormVisible = false;
      });
    },
    getCodeType($index) {
      let item = this.list[$index];
      if (item.type == 1) {
        return "1天";
      } else if (item.type == 2) {
        return "1个月";
      } else if (item.type == 3) {
        return "1年";
      } else {
        return "-";
      }
    },
    checkIfExpired(item) {
      if (item.expirationTime == null || item.expirationTime.length == 0) {
        return false;
      } else if (item.expirationTime < this.getCurrentTime()) {
        return true;
      } else {
        return false;
      }
    },
    getExpirationTime(item) {
      if (item.expirationTime == null || item.expirationTime.length == 0) {
        return "";
      } else {
        return item.expirationTime;
      }
    },
    onSelectTypeClick() {
      console.log(this.typeValue);
      this.getList();
    },
    onSelectExpiredClick() {
      console.log(this.expiredTypeValue);
      this.getList();
    },
    removeCode($index) {
      let _vue = this;
      this.$confirm("确定删除此激活码?", "提示", {
        confirmButtonText: "确定",
        showCancelButton: false,
        type: "warning",
      }).then(() => {
        let item = _vue.list[$index];
        _vue
          .api({
            url: "/wx/code/" + item.id,
            method: "delete",
          })
          .then(() => {
            this.$message.success("删除成功");
            _vue.getList();
          });
      });
    },
    removeMulityCode() {
      if (
        this.multipleSelection == null ||
        this.multipleSelection.length == 0
      ) {
        this.$message.error("请选择要删除的数据");
        return;
      }
      let _vue = this;
      this.$confirm("确定删除所选激活码?", "提示", {
        confirmButtonText: "确定",
        showCancelButton: false,
        type: "warning",
      }).then(() => {
        let codes = "";
        _vue.multipleSelection.forEach((item) => {
          console.log(item.id);
          if (codes != null && codes.length > 0) {
            codes += ",";
          }
          codes += item.id;
        });
        console.log(codes);
        let data = {
          codes: codes,
        };
        _vue
          .api({
            url: "/wx/code/codes",
            method: "delete",
            data,
          })
          .then(() => {
            this.$message.success("删除成功");
            _vue.getList();
          });
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    checkSelect(row, index) {
      let isChecked = true;
      if (row.phone != null && row.phone.length > 0) {
        if (
          row.expirationTime != null &&
          row.expirationTime.length > 0 &&
          row.expirationTime < this.getCurrentTime()
        ) {
          isChecked = true;
          console.log("已过期", row.expirationTime, this.getCurrentTime());
        } else {
          isChecked = false;
          console.log("未过期", row.expirationTime, this.getCurrentTime());
        }
      } else {
        isChecked = true;
        console.log("未激活", "-", this.getCurrentTime());
      }
      return isChecked;
    },
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let dd =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let hh =
        new Date().getHours() < 10
          ? "0" + new Date().getHours()
          : new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      return yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
    },
  },
};
</script>

<style scoped>
.horizonal {
  display: flex;
  flex-direction: row;
}

.vertical {
  display: flex;
  flex-direction: column;
}

.text-expired {
  font-size: 15px;
  font-weight: 700;
  color: red;
}
</style>